package com.hzhk.happyrent.ui.adapter;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.view.ViewGroup;

import com.hzhk.happyrent.R;
import com.hzhk.happyrent.utils.ListUtils;

import java.util.List;

/**
 * User: hzhk(1097282555@qq.com)
 * Date: 2017/12/01
 * Time: 16:38
 * progject: hzk
 * Describe： ${Describe}
 */
public class MainPagerAdapter extends FragmentPagerAdapter {
    private FragmentManager fragmentManager;
    private FragmentTransaction mCurTransaction = null;
    private List<Fragment> fragments;
    private Context context;
    public MainPagerAdapter(FragmentManager fm, List<Fragment> fragments, Context context) {
        super(fm);
        this.fragmentManager = fm;
        this.fragments = fragments;
        this.context=context;
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        mCurTransaction = fragmentManager.beginTransaction();
//        Fragment fragment = getItem(position);
        Fragment fragment = fragmentManager.findFragmentByTag("fragment" + position);
        if(fragment==null){
            fragment=getItem(position);
            mCurTransaction.add(container.getId(), fragment, "fragment" + position);
            mCurTransaction.commit();
        }else{
            mCurTransaction.attach(fragment);
            mCurTransaction.commit();
        }
        return fragment;
    }


    @Override
    public int getCount() {
        return !ListUtils.isEmpty(fragments) ? fragments.size() : 0;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }
}
